﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebCommit.Common.Entitys;
using WebCommit.Common.Enums;
using WebCommit.Common.Helpers;
using NHibernate;

namespace WebCommit.Crawler
{
	public class SaveWorker : Worker
	{
		public SaveWorker(List<WebResourceEntity> webList, object lockObj)
			: base(webList, lockObj)
		{ }

		public override List<WebResourceEntity> PreWork(List<WebResourceEntity> webList)
		{
			List<WebResourceEntity> list = new List<WebResourceEntity>();
			lock (WebListLockObj)
			{
				list = webList.FindAll(w => (w.Saved == false && w.WebCrawlStatus == CrawlStatus.OK && !string.IsNullOrEmpty(w.Title)));
			}

			return list;
		}

		public override List<WebResourceEntity> DoWork(List<WebResourceEntity> webList)
		{
			if (webList.Count < 1)
				return webList;

			lock (WebListLockObj)
			{
				webList.ForEach(new Action<WebResourceEntity>(Update));
			}
			ISession session = NHibernateHelper.GetSession("WebCommit");
			ITransaction tran = session.BeginTransaction();
			foreach (WebResourceEntity web in webList)
			{
				session.Save(web);
			}
			tran.Commit();
			//session.Close();
			return webList;
		}

		public void Update(WebResourceEntity web)
		{
			web.Saved = true;
		}
	}
}
